package com.cjf.aop;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.cjf.aop.annotation.CaptureThrowable;
import com.cjf.aop.annotation.DebugLog;
import com.cjf.aop.annotation.Intercept;
import com.cjf.aop.annotation.SingleClick;
import com.cjf.aop.annotation.WorkThread;
import com.cjf.aop.demo.SecurityCheckAnnotation;
import com.cjf.aop.enums.ThreadType;
import com.cjf.aop.runtime.AOPManager;
import com.cjf.aop.runtime.logger.XLogger;
import com.cjf.aop.runtime.utils.AppExecutors;
import com.cjf.aop.runtime.utils.PermissionUtils;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = MainActivity.class.getSimpleName();
    private int tab;
    TextView mTvHello;


    private MainPresenter presenter;


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tab = 1;
        setContentView(R.layout.activity_main);
        mTvHello = findViewById(R.id.tv_hello);
        presenter = new MainPresenter();
        AOPManager.addLocalOnPermissionDeniedListener(new PermissionUtils.OnPermissionDeniedListener() {
            @Override
            public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied, List<String> permissionsGranted) {
                XLogger.e("申请权限被拒绝局部拦截");
            }
        });
        findViewById(R.id.btn_lambda).setOnClickListener(v -> XLogger.e("lambda表达式点击响应！"));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_single_click:
                handleOnClick(v);
                break;
            case R.id.btn_request_permission:
                presenter.handleRequestPermission(v);
                break;
            case R.id.btn_main_thread:
                AppExecutors.get().poolIO().execute(new Runnable() {
                    @Override
                    public void run() {
                        String s = doInMainThread(v);
                        XLogger.e("子线程内打印主线程返回结果：" + s);
                    }
                });
                break;
            case R.id.btn_io_thread:
                String s = doInIOThread(v);
                mTvHello.setText(s);
             /*   AppExecutors.get().mainThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        mTvHello.setText(s);
                    }
                });*/

                break;
            case R.id.btn_memory_cache:
                //Log.e("xuexiang", "@MemoryCache getMemoryCacheLoginInfo:" + getMemoryCacheLoginInfo());
                break;
            case R.id.btn_disk_cache:
                // Log.e("xuexiang", "@DiskCache getDiskCacheLoginInfo:" + getDiskCacheLoginInfo());
//                testDiskCache1();
//                testDiskCache2();
//                testDiskCache3();
//                testDiskCache4((int) (Math.random() * 100), "1234");
//                testDiskCache5();
                break;
            case R.id.btn_clear_cache:
//                XMemoryCache.getInstance().clear();
//                XDiskCache.getInstance().clear();
                break;
            case R.id.btn_try_catch:
                int result = getNumber();
                mTvHello.setText("结果为:" + result);
                break;
            case R.id.btn_intercept_login:
                doSomeThing();
                break;
            default:
                break;
        }
    }

    @Intercept(MyApplication.INTERCEPT_LOGIN)
    private void doSomeThing() {
        XLogger.e("已经登录了！");
    }


    @CaptureThrowable(MyApplication.TRY_CATCH_KEY)
    private int getNumber() {
        return 100 / 0;
    }


    @SingleClick
    @DebugLog(priority = Log.ERROR)
    public void handleOnClick(View v) {
        XLogger.e("点击响应！");
        //Toast.makeText(MainActivity.this, "你点击了", Toast.LENGTH_SHORT).show();
    }

    @WorkThread(ThreadType.MAIN)
    private String doInMainThread(View v) {
        mTvHello.setText("工作在主线程");
        return "工作在主线程";
    }

    @WorkThread(ThreadType.IO_Single)
    private String doInIOThread(View v) {
        return "io线程名:" + Thread.currentThread().getName();
    }

    @Override
    protected void onResume() {
        super.onResume();

        //checkPhoneState 会检查 app 是否申明了 android.permission.READ_PHONE_STATE 权限
        checkPhoneState();
    }

    @SecurityCheckAnnotation(declaredPermission = "android.permission.READ_PHONE_STATE")
    public void checkPhoneState() {
        //如果不使用 AOP，就得自己来检查权限
        if (!checkPermission("android.permission.READ_PHONE_STATE")) {
            Log.e(TAG, "have no permission to read phone state");
            return;
        }
        Log.e(TAG, "Read Phone State succeed");
        return;
    }

    private boolean checkPermission(String permissionName) {
        try {
            PackageManager pm = getPackageManager();
            //调用 PackageMangaer 的 checkPermission 函数，检查自己是否申明使用某权限
            int nret = pm.checkPermission(permissionName, getPackageName());
            return nret == PackageManager.PERMISSION_GRANTED;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


}
